import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;

@WebServlet("/getVideos")
public class VideoListServlet extends HttpServlet {
    String videoPath;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");
        videoPath = new File(getServletContext().getRealPath("/")) +"\\Video";
        System.out.println(videoPath);
        File dir = new File(videoPath);
        File[] files = dir.listFiles((d, name) -> name.toLowerCase().endsWith(".mp4"));

        List<String> videoList = new ArrayList<>();
        if (files != null) {
            for (File file : files) {
                videoList.add(file.getName());
                System.out.println(file.getName());
            }
        }
        // 使用 Gson 或者手动将列表转换为 JSON 字符串
        String json = new Gson().toJson(videoList);
        System.out.println("返回的 JSON: " + json); // 打印 JSON 数据
        PrintWriter out = response.getWriter();
        out.println(json);
        out.flush();
    }
}
